package com.zyz.forum.interceptor;

import com.zyz.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 把配置文件中存放的登陆页面url获取到
    @Value("${my-forum.login.url}")
    private String loginUrl;
    /**
     * 定义在接口访问之前进行拦截判断
     * @return 是否登录
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断session的有效性
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION_ID) != null) {
            // 用户已登录
            return true;
        }
        // 用户未登录
        // 首先校验要跳转的登陆界面url的正确性
        if (!loginUrl.startsWith("/")) {
            loginUrl = "/" +loginUrl;
        }
        // 跳转至登陆页面
        response.sendRedirect(loginUrl);
        return false;
    }
}
